<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>艺术品列表</title>
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background: #f8f9fa;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        h2 {
            text-align: center;
            color: #333;
            margin: 20px 0;
        }
        .filter {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        .filter input, .filter button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .filter button {
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        .artwork-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        .artwork-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
            padding: 15px;
            transition: transform 0.3s;
        }
        .artwork-card:hover {
            transform: translateY(-5px);
        }
        .artwork-card h3 {
            color: #333;
            margin-bottom: 10px;
        }
        .artwork-card p {
            margin: 5px 0;
            color: #666;
        }
        .price {
            font-weight: bold;
            color: #dc3545;
            margin-top: 10px;
        }
        .actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        .actions button {
            flex: 1;
            padding: 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .collect {
            background: #ffc107;
            color: #333;
        }
        .buy {
            background: #28a745;
            color: white;
        }
        .view {
            background: #007bff;
            color: white;
        }
        .message {
            text-align: center;
            margin: 20px 0;
            color: #666;
            padding: 20px;
        }
        .create-btn {
            display: block;
            margin: 0 0 20px auto;
            padding: 8px 16px;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>艺术品列表</h2>
        <button class="create-btn" onclick="location.href='create_artwork.html'">发布艺术品</button>
        
        <div class="filter">
            <input type="text" id="keyword" placeholder="关键词（标题/创作者）">
            <input type="number" id="minPrice" placeholder="最低价格">
            <input type="number" id="maxPrice" placeholder="最高价格">
            <button onclick="filterArtworks()">筛选</button>
            <button onclick="resetFilter()">重置</button>
        </div>
        
        <div id="artworkList" class="artwork-grid"></div>
        <div id="message" class="message"></div>
        
        <p style="text-align: center; margin-top: 20px;">
            <a href="index.html">返回首页</a>
        </p>
    </div>
    <script>
        // 页面加载时获取所有艺术品
        window.onload = () => {
            // 检查登录状态
            const user = localStorage.getItem('userInfo');
            if (!user) {
                document.querySelector('.create-btn').style.display = 'none';
            }
            fetchArtworks();
        };

        function fetchArtworks(filter = {}) {
            const url = new URL('/artworks/filter', window.location.origin);
            Object.entries(filter).forEach(([k, v]) => {
                if (v) url.searchParams.append(k, v);
            });

            fetch(url)
            .then(res => res.json())
            .then(data => {
                const listEl = document.getElementById('artworkList');
                const msgEl = document.getElementById('message');
                if (data.success && data.artworks.length) {
                    listEl.innerHTML = data.artworks.map(art => `
                        <div class="artwork-card" data-id="${art.artwork_id}">
                            <h3>${art.title}</h3>
                            <p>创作者：${art.creator || '未知'}</p>
                            <p>描述：${art.description || '无'}</p>
                            <p class="price">价格：¥${art.price}</p>
                            <p>卖家：${art.seller_name || '未知'}</p>
                            <div class="actions">
                                <button class="collect" onclick="collectArtwork(${art.artwork_id})">收藏</button>
                                <button class="buy" onclick="buyArtwork(${art.artwork_id}, ${art.owner_id}, ${art.price})">购买</button>
                                <button class="view" onclick="viewArtwork(${art.artwork_id})">详情</button>
                            </div>
                        </div>
                    `).join('');
                    msgEl.textContent = '';
                } else {
                    listEl.innerHTML = '';
                    msgEl.textContent = data.message || '暂无艺术品';
                }
            })
            .catch(err => {
                document.getElementById('message').textContent = '加载失败：' + err;
            });
        }

        function filterArtworks() {
            const keyword = document.getElementById('keyword').value;
            const minPrice = document.getElementById('minPrice').value;
            const maxPrice = document.getElementById('maxPrice').value;
            fetchArtworks({ keyword, minPrice, maxPrice });
        }

        function resetFilter() {
            document.getElementById('keyword').value = '';
            document.getElementById('minPrice').value = '';
            document.getElementById('maxPrice').value = '';
            fetchArtworks();
        }

        function collectArtwork(artworkId) {
            const user = checkLogin();
            if (!user) return;

            fetch('/collection/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ user_id: user.user_id, artwork_id: artworkId })
            })
            .then(res => res.json())
            .then(data => {
                alert(data.message);
            })
            .catch(err => alert('收藏失败：' + err));
        }

        function buyArtwork(artworkId, sellerId, price) {
            const user = checkLogin();
            if (!user) return;

            // 防止用户购买自己的艺术品
            if (user.user_id === sellerId) {
                alert('不能购买自己发布的艺术品');
                return;
            }

            if (confirm(`确定要以 ¥${price} 购买这件艺术品吗？`)) {
                fetch('/transaction/create', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        buyer_id: user.user_id,
                        seller_id: sellerId,
                        artwork_id: artworkId,
                        transaction_price: price
                    })
                })
                .then(res => res.json())
                .then(data => {
                    alert(data.message);
                    if (data.success) {
                        location.href = 'transactions.html';
                    }
                })
                .catch(err => alert('创建订单失败：' + err));
            }
        }

        function viewArtwork(artworkId) {
            location.href = `artwork_detail.html?id=${artworkId}`;
        }

        // 检查登录状态的工具函数
        function checkLogin() {
            const userStr = localStorage.getItem('userInfo');
            if (!userStr) {
                alert('请先登录');
                location.href = 'login.html';
                return null;
            }
            return JSON.parse(userStr);
        }
    </script>
</body>
</html>
